package com.wonderful.compose.overlap

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidViewBinding
import androidx.recyclerview.widget.LinearLayoutManager
import com.wonderful.compose.R
import com.wonderful.compose.databinding.ActivityOverlappingBinding
import com.wonderful.compose.ui.theme.BookingBackground
import com.wonderful.compose.ui.theme.ComposeLearnTheme

/**
 * Desc:
 * @Author: wonderful
 * @Time: 2024/2/19 10:55
 */
class OverlappingActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            ComposeLearnTheme {
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = BookingBackground
                ) {
                    OverlapListView()
                }
            }
        }
    }

    companion object {
        val RESOURCES = listOf(
            R.drawable.img,
            R.drawable.img_1,
            R.drawable.img_2,
            R.drawable.img_3,
            R.drawable.img_4,
            R.drawable.img_5,
            R.drawable.img_6,
            R.drawable.img_7,
            R.drawable.img_8,
            R.drawable.img_9,
            R.drawable.img_10,
            R.drawable.img_11,
            R.drawable.img_12
        )
    }
}

@Preview(showBackground = true)
@Composable
fun OverlapListView() {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .background(Color.White),
        verticalArrangement = Arrangement.Center
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(vertical = 32.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Text(text = "Recycler view overlap items")
            Spacer(modifier = Modifier.height(16.dp))
            RecyclerViewOverlapping()
        }

        Spacer(modifier = Modifier.height(20.dp))

        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(vertical = 32.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Text(text = "Compose overlap items")
            Spacer(modifier = Modifier.height(16.dp))
            ComposeOverlapping()
        }
    }
}

@Composable
fun RecyclerViewOverlapping() {
    val dogsAdapter = DogsAdapter()
    AndroidViewBinding(factory = ActivityOverlappingBinding::inflate) {
        rvDogs.apply {
            layoutManager = LinearLayoutManager(
                this@AndroidViewBinding.root.context,
                LinearLayoutManager.HORIZONTAL,
                false
            )
            adapter = dogsAdapter
            addItemDecoration(OverlappingDecoration())
        }
    }
    dogsAdapter.submitData(OverlappingActivity.RESOURCES)
}

@Composable
fun ComposeOverlapping() {
    LazyRow {
        item { Spacer(modifier = Modifier.width(16.dp)) }

        item {
            OverlapRow(overlapPercentage = 0.2f) {
                for (i in OverlappingActivity.RESOURCES) {
                    Image(
                        painter = painterResource(id = i),
                        contentDescription = "image_$i",
                        contentScale = ContentScale.Crop,
                        modifier = Modifier
                            .size(100.dp)
                            .clip(CircleShape)
                            .border(4.dp, Color(0xFFFFA0A0), CircleShape)
                    )
                }
            }
        }

        item { Spacer(modifier = Modifier.width(16.dp)) }
    }
}

@Composable
fun OverlapRow(
    modifier: Modifier = Modifier,
    overlapPercentage: Float,
    content: @Composable () -> Unit
) {
    // define a factor which determines the width of the item after the next item will overlap on itself
    val factor = 1 - overlapPercentage

    Layout(
        modifier = modifier,
        content = content,
        // define a measurePolicy which determines the size and coordinates of the composables
        // measurables are a list of compositions that can be measured
        // constraints define the range in pixels in which the measured layout would choose a size to render the composition
        measurePolicy = { measurables, constrainsts ->
            val placeableList = measurables.map { it.measure(constrainsts) }
            val height = placeableList.maxOf { it.height }
            // 计算宽度，第一个的加上 第二个开始后的*（1-overlapPercentage)
            val width = (placeableList.subList(1, placeableList.size)
                .sumOf { it.width } * factor + (placeableList.getOrNull(0)?.width ?: 0)).toInt()
            layout(width, height) {
                var x = 0
                for (placeable in placeableList) {
                    placeable.placeRelative(x, 0, 0f)
                    x += (placeable.width * factor).toInt()
                }
            }
        })
}
